/**
 * 首页
 */
import React, { Component } from 'react'
import { connect } from 'react-redux'
import BottomMenu from '../../../../../../../src/js/components/bottomMenu';
import { TabBar, AddrView, AddrList } from 'app/components'
import { Title } from '../../components/common'
import CarPrefixList from '../../components/carPrefixList/pro';
import {
    defaultAddress,
    condition,
    confirmOrder
} from  '../../actions/homeActions'
import {
    InputItem,
    CarInputItem
} from '../../components/home'
import '../../../styles/home.scss';
import common from '../../utils/common'
import { Toast,Modal } from 'antd-mobile'
import style from './index.scss'
const alert = Modal.alert;

const FormCheckRule = {
    carNbrSufRule: /^[a-zA-Z0-9]{4}[a-zA-Z0-9\u4E00-\u9FA5]{1,2}$/,
    carCodeRule: /^[a-zA-Z0-9]{6}$/,
    nameRule: /^[\u4e00-\u9fa5]{2,12}$/,
    telRule: /^[1]{1}[0-9]{10}$/,
    carCodeNullMessage: "请输入车身架号后6位",
    carCodeErrorMessage: "请输入车身架号后6位",
    carNbrSufNullMessage: "请输入车牌号码",
    carNbrSufErrorMessage: "请输正确的车牌号码",
    receivingDddress: "请选择收件人信息"
};

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isShowPreFix: false,  //车牌前缀显
           // 粤S H5X90    119704
            carNumber: "",
            carNumPrefix: "粤A",
            carCode: ""    
        };
    }

    componentWillMount() {
        common.setViewTitle('车辆年检');
        this.setState(
			Object.assign({}, JSON.parse(sessionStorage.getItem('cacheAllState')))
        )
    }

    componentWillUnmount(){
		//离开页面存储全局状态
        sessionStorage.setItem('cacheAllState', JSON.stringify(this.state))
        sessionStorage.removeItem('tagIndex')
    }

    componentDidMount() { 
        // 请求默认地址数据
        this.props.dispatch(defaultAddress({}))
        
        //通过车牌前缀获取办理条件
        let postData = {
			carNumber: this.state.carNumPrefix
        }
        this.props.dispatch(condition(postData))
    }

    componentDidUpdate() {
        /*
		* 兼容ios点击输入框遮挡tag
		* */
		let inputAll = document.getElementsByTagName('input');
		for(let i=0;i<inputAll.length;i++){
			if(inputAll[i].type != 'checkbox'){ //复选框不用设置样式
				inputAll[i].onfocus = () => {
					document.querySelector('.footNavPoise').style.position='static'
				}
				inputAll[i].onblur = () => {
					document.querySelector('.footNavPoise').style.position='fixed'
				}
			}
		}
    }

    // 地址预览组件点击
    addressClick() {
        this.props.router.push('addressList');
    }

    //用户修改车牌前缀后保存车牌前缀
    getName(name) {
        if (name == 1) {
            this.setState({
                isShowPreFix: true,
            })
        } else if (name) {
            this.setState({
                isShowPreFix: false,
                carNumPrefix: name,
            })
            //通过车牌前缀获取办理条件
            let postData = {
                carNumber: name
            }
            this.props.dispatch(condition(postData))
        } else if (!name) {
            this.setState({
                isShowPreFix: false,
            })
        }
    }

    //顶部办理条件
    getTopConditionsText(){
        let conditionArray = this.props.condition.conditionArray;
        return  conditionArray.map((item,i)=>{
                    return <div className={style.conditionsText} key={i}>{item}</div>
                })
    }   
    
     //底部办理条件
     getBottomConditionsText(){
        let docArray = this.props.condition.docArray;
        return  docArray.map((item,i)=>{
                    return <div className={style.conditionsText} key={i}>{item}</div>
                })
    }          
    
    toUrl(url){
        this.props.router.push(url);
    }

    jumpTo(data){
        /** 
         * 目前所有情况有时在线支付，屏蔽补充资料页，不用到付
        */
        // if(common.isToPay(data.carNumPrefix,data['address.cityId'])){
        //     this.toUrl('addInfo')
        // }else{
            this.toUrl('payment')
       // }
    }

    //底部跳转
    bottomHandle(index) {
        if (index == 0) {
            this.props.router.push('/');
        }
        else {
            this.props.router.push('orderList');
        }
    }

    confirmOrder(){
        //粤S H5X90    119704
        let { carNumPrefix,carNumber,carCode } = this.state,
            address = JSON.parse(localStorage.getItem('choiceAddress'));
            
            if(carNumber == ''){
                Toast.info(FormCheckRule.carNbrSufNullMessage,1)
                return;
            }else if (!FormCheckRule.carNbrSufRule.test(carNumber)) {
                Toast.info(FormCheckRule.carNbrSufErrorMessage,1)
                return;
            } else if(carCode == ''){
                Toast.info(FormCheckRule.carCodeNullMessage,1)
                return;
            }else if(!FormCheckRule.carCodeRule.test(carCode)){
                Toast.info(FormCheckRule.carCodeErrorMessage,1)
                return;
            }else if(!address.contactName){
				Toast.info(FormCheckRule.receivingDddress,1);
				return;
            }

        let postData = {
            carNumberSuffix: carNumber,
            carNumPrefix: carNumPrefix,
            carNumber: carNumPrefix + carNumber,
            carCode: carCode,
            'address.contactName': address.contactName,
            'address.cellNum': address.cellNum,
            'address.provinceId': address.provinceId,
            'address.cityId': address.cityId,
            'address.countyId': address.countyId,
            'address.provinceName': address.provinceName,
            'address.cityName': address.cityName,
            'address.countyName': address.contactName,
            'address.street': address.street,
            'address.fullAddr': address.fullAddr.replace(null,''),
        }

        this.props.dispatch(confirmOrder(postData,(result)=>{
            postData['serviceFee'] = result.serviceFee;
            postData['docArray'] = this.props.condition.docArray;
            postData['serviceFeeDesc'] = result.serviceFeeDesc;
            postData['totalChargeFee'] = result.totalChargeFee;
            postData['totalFee'] = result.totalFee;        
            sessionStorage.setItem('payData',JSON.stringify(postData));  //缓存支付页面用

            if (result.hasViolation == 0) {//0/没有 1/有 2/未知
                this.jumpTo(postData);;
            } else if (result.hasViolation == 1) {// 1 有违章
                alert('温馨提示', `系统检测到您的车${postData.carNumber}有未办理违章，请处理完违章再办理年检`, [
                    { text: '确定', onPress: () => console.log('cancel') },
                    {
                        text: '去办年检',
                        onPress: () => {
                            this.jumpTo(postData);
                        },
                        style: {color: '#00B488'}
                    },
                ])
            } else if (result.hasViolation == 2) {//2 未知
                alert('温馨提示', `系统检测不到您的车${postData.carNumber}的违章情况，请确认您的车无违章后再办理年检`, [
                    { text: '确定', onPress: () => console.log('cancel') },
                    {
                        text: '去办年检',
                        onPress: () => {
                            this.jumpTo(postData);
                           
                        },
                        style: {color: '#00B488'}
                    },
                ])
            } else if (result.hasViolation == 3) {//3 年检未到期
                alert('暂不需要年检', `系统检测到${postData.carNumber}检验有效期至：${result.endTime}`, [
                    { text: '确定', onPress: () => console.log('cancel') },
                    {
                        text: '去办年检',
                        onPress: () => {
                            this.jumpTo(postData);
                        },
                        style: {color: '#00B488'}
                    },
                ])
            }
        }))
    }

    render() {
        let { tabBar, car, carCode, carNumPrefix, carNumberSuffix} = this.state,
            cacheAddress;

        if(!this.props.isShowChice||sessionStorage.getItem('isShowChice')){  //选择的地址
			cacheAddress = JSON.parse(localStorage.getItem('choiceAddress'))
		}else {
			cacheAddress = this.props.defaultAddress&&this.props.isShowChice? this.props.defaultAddress:
			JSON.parse(localStorage.getItem('choiceAddress'))?JSON.parse(localStorage.getItem('choiceAddress')):'';  //进入地址列表缓存的地址信息  选择地址的缓存
        }
        
        localStorage.setItem('choiceAddress',JSON.stringify(cacheAddress))
        
        return (
            <div className={style.home}>
                {/*顶部说明-start-*/}
                <div className={style.topExplain}>
                    <img src='./images/tag_icon.png' className={style.labeling}></img>
                    <div className={style.explainText}>
                        <div>新车六年免检服务</div>
                        <div className={style.choiceImg}>
                            <img src='./images/choice_icon.png' className={style.sign}></img>
                            邮政速递上门服务,足不出户办理车辆年检
                        </div>
                        <div className={style.choiceImg}>
                            <img src='./images/choice_icon.png' className={style.sign}></img>
                            支持广东省内各地市              
                        </div>

                    </div>
                </div>
                {/*顶部说明-end-*/}

                <div style={{height: '.24rem'}}></div>
                {/*办理条件-start-*/} 
                <Title text='办理条件' isLine={true}/>
                <div className={style.conditionView}>
                    <div className={style.listBox}>
                        {this.getTopConditionsText()}
                    </div>
                </div>
                {/*办理条件-end-*/} 
                <div style={{height: '.24rem'}}></div>
                {/*车辆信息-start-*/}
                <Title text='车辆信息' isLine={true}/>
                <div className={style.inputItem}>
                    <InputItem type="text" index='2' itemText="车牌号码" maxLength="6" placeHolder="请输入车牌号码" id='carNumber'
                        isShowPreFix = {true} value={this.state.carNumber} showUnderLine={true} showTagText={true}  creditCodeImg={this.state.carNumberImg} creditWidth = {this.state.carNumberWidth}
                        preFixName = {carNumPrefix}
                        isShowPreFixEvent = {()=>{
                            this.setState({
                                isShowPreFix: !this.state.isShowPreFix
                            })
                        }}
                        onClick={()=>{
                            this.setState({
                                carNumber: '',
                                carNumberImg: 'hideDelete',
                                carNumberNoBlur: false
                            })
                            document.querySelector('#carNumber').focus()
                        }}
                        onBlur={(event)=>{
                            let res = event.target.value;
                            this.setState({carNumberNoBlur: true});
                            setTimeout(()=>{
                                if(!this.state.carNumberNoBlur) return;  //点击删除按钮不执行验证
                                let value = res;

                                if(value == ''){
                                    this.setState({
                                        carNumberImg: '',
                                    });
                                }else if(FormCheckRule.carNbrSufRule.test(value)){
                                    this.setState({
                                        carNumberImg: 'correct',
                                        carNumberWidth: '.4rem'
                                    });
                                }else {
                                    this.setState({
                                        carNumberWidth: '.4rem',
                                        carNumberImg: 'error'
                                    })
                                }
                            },0)
                        }}

                        onFocus={(e)=>{
                            window.scrollTo(0, 250);                            
                            let value = e.target.value;
                            if(value.length!=0&&value==this.state.carNumber){
                                this.setState({
                                    carNumberImg: 'showDelete',
                                });
                            }

                        }}

                        onChange={(e) => {
                            let value = e.target.value.replace(/(^\s*)|(\s*$)/g, "").toUpperCase();
                            if(value.length>0&&value!=' '){
                                this.setState({
                                    carNumberImg: 'showDelete',
                                    carNumber: value
                                });
                            }else {
                                this.setState({
                                    carNumberImg: 'hideDelete',
                                    carNumber: value
                                });
                            }
                    }}/>
                    <InputItem type="text" index='2' itemText="车身架号" maxLength="6" placeHolder="请输入车身架号后6位" id='carCode'
                        value={this.state.carCode} showUnderLine={true} showTagText={true}  creditCodeImg={this.state.carCodeImg} creditWidth = {this.state.carCodeWidth}
                        onClick={()=>{
                            this.setState({
                                carCode: '',
                                carCodeImg: 'hideDelete',
                                carCodeNoBlur: false
                            })
                            document.querySelector('#carCode').focus()
                        }}
                        onBlur={(event)=>{
                            let res = event.target.value;
                            this.setState({carCodeNoBlur: true});
                            setTimeout(()=>{
                                if(!this.state.carCodeNoBlur) return;  //点击删除按钮不执行验证
                                let value = res;

                                if(value == ''){
                                    this.setState({
                                        carCodeImg: '',
                                    });
                                }else if(FormCheckRule.carCodeRule.test(value)){
                                    this.setState({
                                        carCodeImg: 'correct',
                                        carCodeWidth: '.4rem'
                                    });
                                }else {
                                    this.setState({
                                        carCodeWidth: '.4rem',
                                        carCodeImg: 'error'
                                    })
                                }
                            },0)
                        }}
                        onFocus={(e)=>{
                            window.scrollTo(0, 250);                                                        
                            let value = e.target.value;
                            if(value.length!=0&&value==this.state.carCode){
                                this.setState({
                                    carCodeImg: 'showDelete',
                                });
                            }

                        }}
                        onChange={(e) => {
                            let value = e.target.value;
                            if(value.length>0&&value!=' '){
                                this.setState({
                                    carCodeImg: 'showDelete',
                                    carCode: e.target.value.replace(/(^\s*)|(\s*$)/g, "").replace("x", 'X')
                                });
                            }else {
                                this.setState({
                                    carCodeImg: 'hideDelete',
                                    carCode: e.target.value.replace(/(^\s*)|(\s*$)/g, "").replace("x", 'X')
                                });
                            }
                    }}/>
                        
                </div>
                {/*车辆信息-end-*/}
                
                <div style={{height: '.24rem'}}></div>

                {/*地址预览*/}
                <AddrView {...cacheAddress} handleClick={() => this.addressClick()} />

                <div style={{height: '.24rem'}}></div>

                {/* 办理流程 */}
                <Title text='办理流程' isLine={true}/>
                <div className={style.processBox}>
                    <div className={style.processItem}>
                        <img src="./images/handle_expllain_1@2x.png" alt=""/>
                        <span>下单申请并支付</span>
                    </div>
                    <div className={style.processLine}></div>
                    <div className={style.processItem}>
                        <img src="./images/handle_expllain_2@2x.png" alt=""/>
                        <span>邮政速递人员上门收取所需资料</span>
                    </div>
                    <div className={style.processLine}></div>
                    <div className={style.processItem}>
                        <img src="./images/handle_expllain_3@2x.png" alt=""/>
                        <span>车管所进行年检业务办理</span>
                    </div>
                    <div className={style.processLine}>
                        <div className={style.notice}>
                            {this.getBottomConditionsText()}
                        </div>
                    </div>
                    <div className={style.processItem}>
                        <img src="./images/handle_expllain_4@2x.png" alt=""/>
                        <span>邮政速递人员回寄办理资料</span>
                    </div>
                </div>
                
                <div style={{height: '.24rem'}}></div>
                <div className={style.btnBox}>
                    <button className={style.subMit} onClick={()=>{this.confirmOrder()}}>
                        立即办理
                    </button>
                </div>

                <CarPrefixList
                    getName={(name)=> this.getName(name)}
                    isShowPreFix={this.state.isShowPreFix}
                />

                <div style={{height: '1.5rem'}}></div>

                 {/*底部固定tab*/}
                 {/* <TabBar {...tabBar} tabClick={(index) => this.tabClick(index)} /> */}

                  {/*底部导航菜单start*/}
                    <BottomMenu onChange={(index) => {
                        this.bottomHandle(index);
                    }} data={[{
                        text: '车辆年检',
                        img: './images/year.png',
                        checkedImg: './images/year_selected.png'
                    }, {text: '我的订单', img: './images/mine.png', checkedImg: './images/mine_selected.png'}]}/>
                    {/*底部导航菜单end*/}
                    
            </div>
        )
    }
}


Home.defaultProps = {
	defaultAddress: {
		fullAddr: '',
		street: ''
    },
    condition:{
        conditionArray: [],
        docArray: []
    }
};


function mapStateToProps(state) {
    return Object.assign({}, state.homeResult,state.addressListResult)       
}

export default connect(mapStateToProps)(Home);

